class printer {

	constructor(ext) {
		Object.assign(this, ext)
		this.start().catch((err) => {
			this.common.alertMsg('启动打印服务失败', '主人~系统启动打印推送服务失败啦', err)
			this.common.writeLog('error', 'start print service failed', false, err)
		})
	}

	resolve(data = 0) {
		return Promise.resolve(data)
	}

	reject(code, msg) {
		return Promise.reject({code, msg})
	}

	async start() {
		this.common.createJob('printService', `*/${this.config.scanInterval || 5} * * * * *`, 
		{
			function: async () => {
				const taskIds = await this.redis.print.scan('print@*', this.config.everyTimePrintCount || 10)
				for(let taskId of taskIds) {
					const result = await this.redis.print.get(taskId, true)
					if(!result || !result.printer || !result.id) {
						console.error('print task invalid', result)
						continue
					}
					console.log(`print ${taskId}`)
					const  {printer, type, id, content, time} = result
					this.print({
						printerCode: printer,
						orderId: id,
						content
					}).then( async () => {
						await this.redis.print.delete(taskId)
					}).catch(err => {
						this.common.alertMsg('打印订单失败啦', `打印机 ${printer} 打印订单 ${type} ${id} 失败啦`, err)
						this.common.writeLog('error', 'print store order failed', false, err)
					})
				}
			}
		}, {
			function: async () => {
				this.common.alertMsg('打印服务已停止','打印服务因为cron而停止')
				this.common.writeLog('error', 'print store order failed', false)
			}
		}, err => {
			console.error(err)
			this.common.alertMsg('打印失败啦','打印机制出错啦', err)
			this.common.writeLog('error', 'print store order failed', false, err)
		}, true)
	}

	print(printData) {
		return new Promise( async (resolve, reject) => {
			try {
				const {orderId, printerCode, content = ''} = printData
				const {clientId, clientSecret} = this.config
				const {accessToken} = await this.common.getAccessToken('gtPrinter')
				const timestamp = this.common.timestamp()
				const {error, error_description, body} = await this.common.reqPost({
					url: 'https://open-api.10ss.net/print/index',
					headers: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						client_id: clientId,
						access_token: accessToken,
						machine_code: printerCode,
						content,
						origin_id: orderId,
						id: this.common.uuid4(),
						timestamp,
						sign: this.common.md5(clientId + timestamp + clientSecret)
					}
				})
				if(error != '0') {
					console.error(error, error_description)
					reject({code: '-2036', msg: `send print request failed [${error}|${error_description}]`})
				}
				const {id, origin_id} = body
				console.log(id, origin_id)
				resolve()
			}
			catch(err) {
				console.error(err)
				reject({code: err.code || '-2036', msg: err.msg || `send print request failed ${err.toString()}`})
			}
		})
	}

}

module.exports = printer